function statement(invoice, plays) {
  let result = `Statement for ${invoice.customer}\n`

  for (let perf of invoice.performances) {
    // print line for this order
    result += ` ${playFor(perf).name}: ${usdMoney(amountFor(perf))} (${perf.audience} seats)\n`
  }

  result += `Amount owed is ${usdMoney(totalAmount())}\n`
  result += `You earned ${totalVolumeCredits()} credits\n`

  return result

  function totalAmount() {
    let totalAmount = 0
    for (let perf of invoice.performances) {
      totalAmount += amountFor(perf)
    }
    return totalAmount
  }

  function totalVolumeCredits() {
    let volumeCredits = 0
    for (let perf of invoice.performances) {
      volumeCredits += volumeCreditsFor(perf)
    }
    return volumeCredits
  }
  // BUG
  function usdMoney(number) {
    const formatNumber = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
    }).format(number / 100)

    return formatNumber
  }

  function volumeCreditsFor(perf) {
    let volumeCredits = Math.max(playFor(perf).audience - 30, 0)
    // add extra credit for every ten comedy attendees
    if ('comedy' === playFor(perf).type) volumeCredits += Math.floor(perf.audience / 5)

    return volumeCredits
  }

  function playFor(aPerformance) {
    return plays[aPerformance.playID]
  }
  function amountFor(perf) {
    let thisAmount = 0
    let play = playFor(perf)
    switch (play.type) {
      case 'tragedy':
        thisAmount = 40000
        if (perf.audience > 30) {
          thisAmount += 1000 * (perf.audience - 30)
        }
        break
      case 'comedy':
        thisAmount = 30000
        if (perf.audience > 20) {
          thisAmount += 10000 + 500 * (perf.audience - 20)
        }
        thisAmount += 300 * perf.audience
        break
      default:
        throw new Error(`unknown type: ${play.type}`)
    }
    return thisAmount
  }
}
export default statement
